<template>
    <div class="capture-wrapper">
        <div class="capture-toolbar">
            <el-input class="capture-search-box" placeholder="经纬度坐标" suffix-icon="Search" size="small"
                v-model="_location" round></el-input>
            <div class="capture-btn-wrapper">
                <el-button :icon="DocumentAdd" size="small" @click="handleImport()" plain>导入</el-button>
                <el-button type="danger" :icon="Delete" size="small" @click="handleDelete()" plain>删除</el-button>
            </div>
        </div>
        <div class="explorer-container">
            <!-- 左侧边栏 -->
            <div class="sidebar">
                <div v-for="directory in directories" :key="directory" class="directory-item"
                    :class="{ active: activeDirectory === directory }" @click="handleDirectorySelect(directory)">
                    <span class="directory-icon">📁</span>
                    <span class="directory-name">{{ directory }}</span>
                </div>
            </div>
            <!-- 右侧内容 -->
            <div class="content">
                <div class="image-gallery">
                    <div v-for="image in images" :key="image.imageFile" class="image-item"
                        @click="handleImageClick(image)">
                        <img :src="getImageUrl(image.imagePath)" :alt="image.imageFile" />
                        <div class="image-metadata">
                            <p>Lat: {{ image.metadata.centerLat }}</p>
                            <p>Lng: {{ image.metadata.centerLng }}</p>
                            <p>Zoom: {{ image.metadata.zoom }}</p>
                            <p>Altitude: {{ image.metadata.altitude }}</p>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 图片预览遮罩 -->
            <div v-if="dialogVisible" class="image-preview-overlay" @click="dialogVisible = false">
                <div class="preview-container">
                    <div class="metadata-display">
                        <p>Lat: {{ selectedImageMetadata.centerLat }}</p>
                        <p>Lng: {{ selectedImageMetadata.centerLng }}</p>
                        <p>Zoom: {{ selectedImageMetadata.zoom }}</p>
                        <p>Altitude: {{ selectedImageMetadata.altitude }}</p>
                    </div>
                    <img :src="selectedImage" class="preview-image" />
                    <button v-if="showPrevButton" class="nav-button prev-button"
                        @click.stop="showPreviousImage">&#10094;</button>
                    <button v-if="showNextButton" class="nav-button next-button"
                        @click.stop="showNextImage">&#10095;</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import API from '@/js/api';
import { ref, onMounted, onUnmounted } from 'vue';
import { DocumentAdd, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 定义跳转的经纬度坐标
const _location = ref('');

// 目录数据
const directories = ref([]);
const images = ref([]);

// 当前选中的目录
const activeDirectory = ref('');
const dialogVisible = ref(false);
const selectedImage = ref('');
const selectedImageMetadata = ref({});
const selectedImageIndex = ref(-1); // 当前预览图像的索引
const showPrevButton = ref(true);
const showNextButton = ref(true);

// 导入时候展示loading进展
let loading = null;

// 获取图像 URL
const getImageUrl = (image_path) => {
    return API.api_url('LoadImage', { image_path });
};

// 处理目录选择
const handleDirectorySelect = async (dir) => {
    activeDirectory.value = dir;
    let result = await API.invoke('GetCaptureImages', { dir });
    if (result.code == 0) {
        images.value = result.msg;
    } else {
        ElMessage.error(result.msg);
    }
};

// 处理图像点击
const handleImageClick = (image) => {
    const index = images.value.findIndex(img => img.imagePath === image.imagePath);
    if (index !== -1) {
        selectedImageIndex.value = index;
        selectedImage.value = getImageUrl(image.imagePath);
        selectedImageMetadata.value = image.metadata;
        dialogVisible.value = true;

        // 初始化箭头显示状态
        showPrevButton.value = index > 0;
        showNextButton.value = index < images.value.length - 1;
    }
};

// 显示上一张图像
const showPreviousImage = () => {
    if (selectedImageIndex.value > 0) {
        selectedImageIndex.value--;
        const prevImage = images.value[selectedImageIndex.value];
        selectedImage.value = getImageUrl(prevImage.imagePath);
        selectedImageMetadata.value = prevImage.metadata;

        // 更新箭头显示状态
        showPrevButton.value = selectedImageIndex.value > 0;
        showNextButton.value = true;
    } else {
        // ElMessage('已经是第一张图片');
    }
};

// 显示下一张图像
const showNextImage = () => {
    if (selectedImageIndex.value < images.value.length - 1) {
        selectedImageIndex.value++;
        const nextImage = images.value[selectedImageIndex.value];
        selectedImage.value = getImageUrl(nextImage.imagePath);
        selectedImageMetadata.value = nextImage.metadata;

        // 更新箭头显示状态
        showNextButton.value = selectedImageIndex.value < images.value.length - 1;
        showPrevButton.value = true;
    } else {
        // ElMessage('已经是最后一张图片');
    }
};

// 键盘事件处理
const handleKeyDown = (event) => {
    if (event.key === 'Escape') {
        dialogVisible.value = false;
    } else if (event.key === 'ArrowLeft') {
        showPreviousImage();
    } else if (event.key === 'ArrowRight') {
        showNextImage();
    }
};

// 获取目录列表
async function getDirectories() {
    let result = await API.invoke('GetCaptureDirs', {});
    if (result.code == 0) {
        directories.value = result.msg;
    } else {
        ElMessage.error(result.msg);
    }
}

// 获取当前目录的图像列表
async function getCaptureImages(dir) {
    let result = await API.invoke('GetCaptureImages', { dir });
    if (result.code == 0) {
        images.value = result.msg;
    } else {
        ElMessage.error(result.msg);
    }
}

// 对于瓦片记录的处理函数
async function handleImport() {
    let result = await API.invoke('ImportCaptures', {
        dir: activeDirectory.value
    });
    if (result.code == 0) {
        // console.log(result);
        if (!loading) {
            loading = ElLoading.service({
                lock: true,
                text: '开始导入截图...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        }
    } else {
        ElMessage.error(result.msg);
    }
}

async function handleDelete() {
    try {
        await ElMessageBox.confirm(
            `确定要删除目录${activeDirectory.value}么？`,
            '提示',
            {
                confirmButtonText: '确 定',
                cancelButtonText: '取 消',
                type: 'warning',
            }
        );

        // 确认删除目录，调用接口删除并提示对应的结果
        let result = await API.invoke('DeleteCaptureImages', {
            dir: activeDirectory.value
        });
        if (result.code == 0) {
            ElMessage.success(`删除目录${activeDirectory.value}成功！`);
            await getCaptures();
        } else {
            ElMessage.error(result.msg);
        }
    } catch (error) { }
}

// 获取到最新的目录和信息
async function getCaptures() {
    await getDirectories();
    if (directories.value.length > 0) {
        activeDirectory.value = directories.value[0];
        await getCaptureImages(directories.value[0]);
    }
}

async function onWsMessage(message) {
    // console.log('Captures::onWsMessage message = ', message);
    let data = JSON.parse(message);
    if (data.event === 'import_status') {
        loading && loading.setText(data.data);
    } else if (data.event === 'import_end') {
        loading && loading.close();
        loading = null;
        ElMessage.success('截图导入完成！')
    }
}

// 组件挂载时初始化
onMounted(async () => {
    await getCaptures();
    window.addEventListener('keydown', handleKeyDown);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown);
});

defineExpose({ onWsMessage });
</script>

<style scoped>
.capture-wrapper {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: block;
}

.explorer-container {
    display: flex;
    height: 100vh;
    background-color: #f5f5f5;
}

.sidebar {
    width: 200px;
    height: calc(100% - 90px);
    background-color: #2d2d2d;
    color: #fff;
    padding: 10px;
    box-sizing: border-box;
    overflow-y: auto;
}

.directory-item {
    display: flex;
    align-items: center;
    padding: 8px;
    cursor: pointer;
    border-radius: 4px;
    margin-bottom: 4px;
    transition: background-color 0.2s;
}

.directory-item:hover {
    background-color: #3d3d3d;
}

.directory-item.active {
    background-color: #4d4d4d;
}

.directory-icon {
    margin-right: 8px;
}

.directory-name {
    font-size: 14px;
}

.content {
    flex: 1;
    padding: 20px;
    background-color: #fff;
    box-sizing: border-box;
    height: calc(100% - 90px);
    overflow-y: auto;
}

.image-gallery {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.image-item {
    flex: 1 1 calc(25% - 10px);
    min-width: 200px;
    max-width: calc(25% - 10px);
    cursor: pointer;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
    transition: transform 0.2s, box-shadow 0.2s;
}

.image-item img {
    width: 100%;
    height: auto;
    display: block;
}

.image-item:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.image-metadata {
    padding: 8px;
    background-color: #f9f9f9;
    border-top: 1px solid #ddd;
    font-size: 12px;
}

.image-preview-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.preview-container {
    position: relative;
    max-width: 90%;
    max-height: 90%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.metadata-display {
    position: absolute;
    top: 10px;
    left: 10px;
    background-color: rgba(0, 0, 0, 0.7);
    color: #fff;
    padding: 10px;
    border-radius: 4px;
    z-index: 1001;
    font-size: 12px;
}

.preview-image {
    max-width: 100%;
    max-height: 100%;
    border-radius: 4px;
}

.nav-button {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    border: none;
    padding: 10px;
    cursor: pointer;
    font-size: 24px;
    z-index: 1002;
}

.prev-button {
    left: 10px;
}

.next-button {
    right: 10px;
}

.capture-toolbar {
    display: flex;
    background-color: rgb(249, 248, 248);
    align-items: center;
    padding: 10px;
    width: 100%;
    height: 40px;
    box-sizing: border-box;
}

.capture-search-box {
    width: 250px;
    border-radius: 10px;
}

.capture-btn-wrapper {
    display: flex;
    position: absolute;
    right: 10px;
}
</style>